package cn.wang.controller;

import cn.wang.common.vo.PageResult;
import cn.wang.pojo.Sku;
import cn.wang.pojo.Spu;
import cn.wang.pojo.SpuDetail;
import cn.wang.service.IGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class GoodsController {
    @Autowired
    private IGoodsService goodsService;

    /**
     * 分页查询spu
     *
     * @param key
     * @param saleable
     * @param page
     * @param rows
     * @return
     */
    @GetMapping("/spu/page")
    public ResponseEntity<PageResult<Spu>> queryGoodsByPage(
            @RequestParam(value = "key", required = false) String key,
            @RequestParam(value = "saleable", required = false) Boolean saleable,
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "rows", defaultValue = "5") Integer rows
    ) {
        return ResponseEntity.ok(goodsService.queryGoodsByPage(key, saleable, page, rows));
    }

    /**
     * 根据spu的id查询spu
     * @param spuId
     * @return
     */
    @GetMapping("/spu/id")
    ResponseEntity<Spu> queryGoodBySpuId(@RequestParam("id") Long spuId){
        return  ResponseEntity.ok(goodsService.queryGoodBySpuId(spuId));
    }

    /**
     * 保存商品
     *
     * @param spu
     * @return
     */
    @PostMapping("/goods")
    public ResponseEntity<Void> saveGoods(@RequestBody Spu spu) {
        goodsService.saveSpu(spu);
        return ResponseEntity.status(HttpStatus.CREATED).body(null);
    }

    /**
     * 根据spuid 参数spuDetqail
     *
     * @param spuId
     * @return
     */
    @GetMapping("/spu/detail/{spuId}")
    public ResponseEntity<SpuDetail> querySpuBySpuId(@PathVariable("spuId") Long spuId) {
        return ResponseEntity.ok(goodsService.querySpuBySpuId(spuId));
    }

    /**
     * 根据spuid获取所有的sku
     * @param id
     * @return
     */
    @GetMapping("/sku/list")
    public ResponseEntity<List<Sku>> querySkusBySpuId(@RequestParam("id") Long id) {
        return ResponseEntity.ok(goodsService.querySkusBySpuId(id));
    }

    @PutMapping("/goods")
    public ResponseEntity<Void> updateGoods(@RequestBody Spu spu){
        goodsService.updateGoods(spu);
        return ResponseEntity.status(HttpStatus.RESET_CONTENT).body(null);
    }
}
